package com.codedancer.campus.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codedancer.campus.common.exception.BusinessException;
import com.codedancer.campus.manager.service.IHeadlineNesService;
import com.codedancer.campus.manager.service.bo.headlineNews.HeadlineNewsPageSearchBo;
import com.codedancer.campus.manager.service.vo.headlineNews.HeadlineNewsPageVo;
import com.codedancer.campus.manager.service.vo.headlineNews.HeadlineNewsVo;
import com.codedancer.campus.mapper.HeadlineNewsMapper;
import com.codedancer.campus.po.HeadlineNews;
import com.codedancer.campus.qo.headlineNews.HeadlineNewsPageSearchQo;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class HeadlineNesServiceImpl implements IHeadlineNesService {

    @Autowired
    private HeadlineNewsMapper headlineNewsMapper;

    /**
     * 分页查询头条新闻
     *
     * @param headlineNewsPageSearchBo
     * @return
     */
    @Override
    public IPage<HeadlineNewsPageVo> page(HeadlineNewsPageSearchBo headlineNewsPageSearchBo) {
        HeadlineNewsPageSearchQo headlineNewsPageSearchQo = BeanUtil.copyProperties(
            headlineNewsPageSearchBo, HeadlineNewsPageSearchQo.class);
        IPage<HeadlineNews> headlineNewsIPage = headlineNewsMapper.page2Manager(
            new Page<HeadlineNews>(headlineNewsPageSearchBo.getPage(),
                headlineNewsPageSearchBo.getSize()), headlineNewsPageSearchQo);
        List<HeadlineNewsPageVo> headlineNewsPageVos;
        IPage<HeadlineNewsPageVo> headlineNewsPageVoIPage = new Page<>();
        headlineNewsPageVos = headlineNewsIPage.getRecords().stream().map(headlineNews -> {
            return BeanUtil.copyProperties(headlineNews, HeadlineNewsPageVo.class);
        }).collect(Collectors.toList());
        headlineNewsPageVoIPage.setRecords(headlineNewsPageVos);
        headlineNewsPageVoIPage.setTotal(headlineNewsIPage.getTotal());
        return headlineNewsPageVoIPage;
    }

    /**
     * 头条新闻详情
     *
     * @param uuid
     * @return
     */
    @Override
    public HeadlineNewsVo detail(String uuid) {
        HeadlineNews headlineNews = headlineNewsMapper.findById(uuid)
            .orElseThrow(() -> new BusinessException("头条新闻不存在"));
        return BeanUtil.copyProperties(headlineNews, HeadlineNewsVo.class);
    }

    /**
     * 删除头条新闻
     *
     * @param uuid
     */
    @Override
    public void delete(String uuid) {
        if (!headlineNewsMapper.existsByUuId(uuid)) {
            throw new BusinessException("头条新闻不存在");
        }
        headlineNewsMapper.deleteById(uuid);
    }
}
